package cn.iocoder.yudao.module.eval.service.candidate;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.eval.controller.admin.candidate.vo.EvalCandidateMaterialPageReqVO;
import cn.iocoder.yudao.module.eval.controller.admin.candidate.vo.EvalCandidateMaterialSaveReqVO;
import cn.iocoder.yudao.module.eval.dal.dataobject.candidate.EvalCandidateMaterialDO;
import cn.iocoder.yudao.module.eval.dal.mysql.candidate.EvalCandidateMaterialMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.eval.enums.ErrorCodeConstants.*;

/**
 * 参评人员材料 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class EvalCandidateMaterialServiceImpl implements EvalCandidateMaterialService {

    @Resource
    private EvalCandidateMaterialMapper candidateMaterialMapper;

    @Override
    public Long createCandidateMaterial(EvalCandidateMaterialSaveReqVO createReqVO) {
        // 插入
        EvalCandidateMaterialDO candidateMaterial = BeanUtils.toBean(createReqVO, EvalCandidateMaterialDO.class);
        candidateMaterial.setUploadTime(LocalDateTime.now());
        candidateMaterial.setMaterialStatus(1); // 待审核
        candidateMaterialMapper.insert(candidateMaterial);
        // 返回
        return candidateMaterial.getId();
    }

    @Override
    public void updateCandidateMaterial(EvalCandidateMaterialSaveReqVO updateReqVO) {
        // 校验存在
        validateCandidateMaterialExists(updateReqVO.getId());
        
        // 更新
        EvalCandidateMaterialDO updateObj = BeanUtils.toBean(updateReqVO, EvalCandidateMaterialDO.class);
        candidateMaterialMapper.updateById(updateObj);
    }

    @Override
    public void deleteCandidateMaterial(Long id) {
        // 校验存在
        validateCandidateMaterialExists(id);
        // 删除
        candidateMaterialMapper.deleteById(id);
    }

    private void validateCandidateMaterialExists(Long id) {
        if (candidateMaterialMapper.selectById(id) == null) {
            throw exception(CANDIDATE_MATERIAL_NOT_EXISTS);
        }
    }

    @Override
    public EvalCandidateMaterialDO getCandidateMaterial(Long id) {
        return candidateMaterialMapper.selectById(id);
    }

    @Override
    public List<EvalCandidateMaterialDO> getCandidateMaterialList(Collection<Long> ids) {
        return candidateMaterialMapper.selectList("id", ids);
    }

    @Override
    public PageResult<EvalCandidateMaterialDO> getCandidateMaterialPage(EvalCandidateMaterialPageReqVO pageReqVO) {
        return candidateMaterialMapper.selectPage(pageReqVO);
    }

    @Override
    public List<EvalCandidateMaterialDO> getCandidateMaterialList(EvalCandidateMaterialPageReqVO exportReqVO) {
        return candidateMaterialMapper.selectList(exportReqVO);
    }

    @Override
    public List<EvalCandidateMaterialDO> getCandidateMaterialListByCandidateId(Long candidateInfoId) {
        return candidateMaterialMapper.selectListByCandidateInfoId(candidateInfoId);
    }

    @Override
    public void auditCandidateMaterial(Long id, Integer auditStatus, String auditComments) {
        // 校验存在
        validateCandidateMaterialExists(id);
        
        // 更新审核信息
        EvalCandidateMaterialDO updateObj = new EvalCandidateMaterialDO();
        updateObj.setId(id);
        updateObj.setAuditStatus(auditStatus);
        updateObj.setAuditComments(auditComments);
        updateObj.setAuditTime(LocalDateTime.now());
        candidateMaterialMapper.updateById(updateObj);
    }

    @Override
    public void batchAuditCandidateMaterial(List<Long> ids, Integer auditStatus, String auditComments) {
        for (Long id : ids) {
            auditCandidateMaterial(id, auditStatus, auditComments);
        }
    }

    @Override
    public Object checkMaterialCompleteness(Long candidateInfoId) {
        List<EvalCandidateMaterialDO> materials = candidateMaterialMapper.selectListByCandidateInfoId(candidateInfoId);
        
        // 定义必需材料类型
        List<Integer> requiredMaterialTypes = List.of(1, 2, 3, 4); // 身份证、学历证明、工作证明、照片
        
        Map<String, Object> result = new HashMap<>();
        List<String> missingMaterials = new ArrayList<>();
        List<String> pendingMaterials = new ArrayList<>();
        
        for (Integer requiredType : requiredMaterialTypes) {
            boolean hasRequired = materials.stream()
                    .anyMatch(m -> m.getMaterialType().equals(requiredType) && m.getAuditStatus() == 2);
            
            if (!hasRequired) {
                boolean hasPending = materials.stream()
                        .anyMatch(m -> m.getMaterialType().equals(requiredType) && m.getAuditStatus() == 1);
                
                String materialName = getMaterialTypeName(requiredType);
                if (hasPending) {
                    pendingMaterials.add(materialName);
                } else {
                    missingMaterials.add(materialName);
                }
            }
        }
        
        result.put("isComplete", missingMaterials.isEmpty() && pendingMaterials.isEmpty());
        result.put("missingMaterials", missingMaterials);
        result.put("pendingMaterials", pendingMaterials);
        result.put("totalMaterials", materials.size());
        result.put("approvedMaterials", materials.stream().filter(m -> m.getAuditStatus() == 2).count());
        
        return result;
    }

    /**
     * 获取材料类型名称
     */
    private String getMaterialTypeName(Integer materialType) {
        Map<Integer, String> typeMap = Map.of(
            1, "身份证",
            2, "学历证明", 
            3, "工作证明",
            4, "个人照片",
            5, "培训证书",
            6, "其他材料"
        );
        return typeMap.getOrDefault(materialType, "未知材料");
    }

}
